<template>
  <div class="app-container">
    <div class="app-container_title">{{ useTitle() }}</div>
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="任务名称" prop="task_name">
        <el-input
          v-model="queryParams.task_name"
          placeholder="请输入任务名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务ID" prop="task_id">
        <el-input
          v-model="queryParams.task_id"
          placeholder="请输入任务ID"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="task_status">
        <el-select
          v-model="queryParams.task_status"
          placeholder="任务状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd"
          >新建任务</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Delete"
          :disabled="multiple"
          @click="handleBatchDelete"
          >批量删除</el-button
        >
      </el-col>
      <!-- <right-toolbar v-model:showSearch="showSearch"></right-toolbar> -->
      <!-- @queryTable="getList" -->
    </el-row>

    <!-- 表格数据 -->
    <div class="table-wrapper">
      <div class="table-wrapper_main">
        <el-table
          v-loading="loading"
          :data="taskList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="任务ID" prop="task_id">
            <template #default="scope">
              <el-button
                link
                type="primary"
                class="task-id-link"
                @click="handleTaskIdClick(scope.row)"
              >
                {{ scope.row.task_id }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="任务名称" prop="task_name" />
          <el-table-column label="任务状态" prop="status">
            <template #default="scope">
              <el-tag>{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="created_at">
            <template #default="scope">
              <span>{{ scope.row.created_at || scope.row.create_time }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="编辑任务" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click.stop="handleUpdate(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除任务" placement="top">
                <el-button
                  link
                  type="danger"
                  icon="Delete"
                  @click.stop="handleDelete(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="下载模型" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Download"
                  @click.stop="handleDownload(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="执行训练" placement="top">
                <el-button
                  link
                  type="success"
                  icon="VideoCamera"
                  @click.stop="handleExecute(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="取消训练"
                placement="top"
                v-if="
                  scope.row.task_status === '运行中' ||
                  scope.row.task_status === '等待'
                "
              >
                <el-button
                  link
                  type="warning"
                  icon="CircleClose"
                  @click.stop="handleCancel(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="重试训练"
                placement="top"
                v-if="scope.row.task_status === 'FAILED'"
              >
                <el-button
                  link
                  type="primary"
                  icon="Refresh"
                  @click.stop="handleRetry(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="部署模型"
                placement="top"
                v-if="scope.row.task_status === 'SUCCESS'"
              >
                <el-button
                  link
                  type="primary"
                  icon="Upload"
                  @click.stop="handleDeploy(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 编辑任务弹窗（结构与新建任务 create.vue 保持一致） -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="editForm" :model="form" :rules="rules" label-width="120px">
        <!-- 基本任务配置 -->
        <div class="form-section">
          <h3 class="section-title">基本任务配置</h3>

          <!-- 任务名称 -->
          <el-form-item label="任务名称" prop="task_name">
            <el-input v-model="form.task_name" placeholder="请输入任务名称" />
          </el-form-item>

          <!-- 算法选择（显示算法 file_id，只读） -->
          <el-form-item label="算法选择" prop="algorithm">
            <el-input
              v-model="form.algorithm"
              placeholder="请输入算法（file_id）"
              disabled
            />
          </el-form-item>

          <!-- 项目选择（输入框 + 只读） -->
          <el-form-item label="项目选择" prop="project">
            <el-input
              v-model="form.project"
              placeholder="请输入项目"
              disabled
            />
          </el-form-item>

          <!-- 场景选择（输入框 + 只读） -->
          <el-form-item label="场景选择" prop="scenario">
            <el-input
              v-model="form.scenario"
              placeholder="请输入场景"
              disabled
            />
          </el-form-item>

          <!-- 版本选择（输入框 + 只读） -->
          <el-form-item label="版本选择" prop="version">
            <el-input
              v-model="form.version"
              placeholder="请输入版本"
              disabled
            />
          </el-form-item>

          <!-- 任务描述 -->
          <el-form-item label="任务描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              placeholder="请输入任务描述"
            />
          </el-form-item>
        </div>

        <!-- 数据配置（与新建任务保持一致） -->
        <div class="form-section">
          <h3 class="section-title">数据配置</h3>

          <!-- 环境选择 -->
          <el-form-item label="环境选择" prop="envSelection">
            <el-select
              v-model="form.envSelection"
              placeholder="请选择环境"
              style="width: 100%"
              @change="handleEnvSelectionChange"
            >
              <el-option
                v-for="item in envSelectionOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <!-- API方法 -->
          <el-form-item label="API方法" prop="apiMethod">
            <el-select
              v-model="form.apiMethod"
              placeholder="请选择API方法"
              style="width: 100%"
            >
              <el-option
                v-for="item in apiMethodOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <!-- API Host -->
          <el-form-item label="API Host" prop="apiHost">
            <el-input v-model="form.apiHost" placeholder="请输入API Host" />
          </el-form-item>

          <!-- API路径 -->
          <el-form-item label="API路径" prop="apiDataPath">
            <el-input v-model="form.apiDataPath" placeholder="请输入API路径" />
          </el-form-item>

          <!-- 请求类 -->
          <el-form-item label="请求类" prop="dataRequestClass">
            <el-input
              v-model="form.dataRequestClass"
              placeholder="请输入请求类"
            />
          </el-form-item>

          <!-- 响应类 -->
          <el-form-item label="响应类" prop="dataResponseClass">
            <el-input
              v-model="form.dataResponseClass"
              placeholder="请输入响应类"
            />
          </el-form-item>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
import { ref, reactive, getCurrentInstance, onMounted, toRefs } from "vue";
import { useTitle } from "@/utils/dynamicTitle";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { parseTime } from "@/utils/ruoyi";
import {
  listTrainingTasks,
  searchTrainingTasks,
  getTrainingStatus,
  getTrainingTask,
  executeTrainingTask,
  cancelTrainingTask,
  retryTrainingTask,
  delTrainingTask,
  delTrainingTaskBatch,
  downloadTrainingModel,
} from "@/api/training";
import { getAlgorithm } from "@/api/algorithm";

const router = useRouter();
const { proxy } = getCurrentInstance();

const taskList = ref([]);
const open = ref(false);
const total = ref(0);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const editForm = ref(null);

// 状态选项
const statusOptions = ref([]);

const data = reactive({
  form: {
    task_name: "",
    project: "",
    scenario: "",
    algorithm: "",
    version: "",
    description: "",
    // 数据配置（与 create.vue 中字段命名保持一致）
    envSelection: "",
    apiMethod: "",
    apiHost: "",
    apiDataPath: "",
    dataRequestClass: "",
    dataResponseClass: "",
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    task_id: "",
    task_name: "",
    task_status: "",
  },
  rules: {
    task_name: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
    description: [
      { required: true, message: "请输入任务描述", trigger: "blur" },
    ],
  },
  // 环境选择选项（与 create.vue 保持一致）
  envSelectionOptions: [
    { value: "testing", label: "测试环境" },
    { value: "production", label: "生产环境" },
  ],
  // API 方法选项（与 create.vue 保持一致）
  apiMethodOptions: [
    { value: "GET", label: "GET" },
    { value: "POST", label: "POST" },
    { value: "PUT", label: "PUT" },
    { value: "DELETE", label: "DELETE" },
  ],
});

const { queryParams, form, rules, envSelectionOptions, apiMethodOptions } =
  toRefs(data);

// 当前任务关联算法的完整配置（用于环境切换时展示 dev_env）
const currentAlgorithmDetail = ref(null);

/** 获取训练状态列表 */
async function getStatusOptions() {
  try {
    const response = await getTrainingStatus();
    // BentoML 接口返回的状态选项
    statusOptions.value = response || [];
  } catch (error) {
    console.error("获取训练状态失败:", error);
    statusOptions.value = ["等待", "运行中", "SUCCESS", "FAILED"]; // 默认值
  }
}

/** 查询训练任务列表 */
async function getList() {
  loading.value = true;
  try {
    // 检查是否有搜索条件
    const hasSearchConditions =
      queryParams.value.task_id ||
      queryParams.value.task_name ||
      queryParams.value.task_status;

    let response;
    if (hasSearchConditions) {
      // 使用搜索接口
      const searchParams = {
        task_id: queryParams.value.task_id || null,
        task_name: queryParams.value.task_name || null,
        task_status: queryParams.value.task_status || null,
      };
      response = await searchTrainingTasks(searchParams, 100);
    } else {
      // 使用列表接口
      response = await listTrainingTasks({
        status: null,
        limit: 100,
      });
    }

    // BentoML 接口返回的是数组格式
    taskList.value = response.tasks || [];
    total.value = response.total || 0;
  } catch (error) {
    console.error("获取训练任务列表失败:", error);
    ElMessage.error("获取训练任务列表失败");
    taskList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
async function handleDelete(row) {
  const taskIds = row.task_id || ids.value;
  try {
    await ElMessageBox.confirm(
      '是否确认删除任务编号为"' + taskIds + '"的数据项?',
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await delTrainingTask(taskIds);
    getList();
    ElMessage.success("删除成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除任务失败:", error);
      ElMessage.error("删除任务失败");
    }
  }
}

/** 批量删除按钮操作 */
async function handleBatchDelete() {
  if (ids.value.length === 0) {
    ElMessage.warning("请选择要删除的任务");
    return;
  }

  try {
    await ElMessageBox.confirm(
      "是否确认删除选中的" + ids.value.length + "条数据?",
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await delTrainingTaskBatch(ids.value);
    getList();
    ElMessage.success("删除成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除任务失败:", error);
      ElMessage.error("批量删除任务失败");
    }
  }
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.task_id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    task_name: "",
    project: "",
    scenario: "",
    algorithm: "",
    version: "",
    description: "",
    envSelection: "",
    apiMethod: "",
    apiHost: "",
    apiDataPath: "",
    dataRequestClass: "",
    dataResponseClass: "",
  };
  currentAlgorithmDetail.value = null;
}

/** 添加任务 */
function handleAdd() {
  router.push("/model/training/create");
}

// 根据环境选择回显 API 配置（复用 create.vue 的逻辑）
function fillApiConfigFromEnv(apiEnv) {
  if (!apiEnv) return;

  form.value.apiMethod = apiEnv.api_method || "";
  form.value.apiHost = apiEnv.api_host || "";
  form.value.apiDataPath = apiEnv.api_path || "";
  form.value.dataRequestClass = apiEnv.request_class || "";
  form.value.dataResponseClass = apiEnv.response_class || "";
}

// 环境切换：在已有算法 dev_env 的基础上切换测试 / 生产配置
function handleEnvSelectionChange(envValue) {
  if (!currentAlgorithmDetail.value || !currentAlgorithmDetail.value.dev_env) {
    return;
  }

  const devEnv = currentAlgorithmDetail.value.dev_env;
  let apiEnv = null;

  if (envValue === "testing" && devEnv.testing_env) {
    apiEnv = devEnv.testing_env;
  } else if (envValue === "production" && devEnv.production_env) {
    apiEnv = devEnv.production_env;
  }

  if (apiEnv) {
    fillApiConfigFromEnv(apiEnv);
  } else {
    // 选中环境没有配置时，清空显示
    form.value.apiMethod = "";
    form.value.apiHost = "";
    form.value.apiDataPath = "";
    form.value.dataRequestClass = "";
    form.value.dataResponseClass = "";
  }
}

/** 修改任务 */
async function handleUpdate(row) {
  reset();
  open.value = true;
  title.value = "编辑任务";

  try {
    // 获取任务详情（BentoML 返回的任务详情结构）
    const response = await getTrainingTask(row.task_id);
    const taskDetail = response || {};

    // 根据你提供的返回结构：
    // {
    //   "task_id": "...",
    //   "task_name": "...",
    //   "hyperparameters": { "project": "...", "scenario": "...", "version": "..." },
    //   "algorithm_file_id": "...",
    //   ...
    // }

    const hyper = taskDetail.hyperparameters || {};

    // 回显“基本任务配置”字段（与 create.vue 对齐）
    Object.assign(form.value, {
      task_id: taskDetail.task_id || row.task_id,
      task_name: taskDetail.task_name || "",
      project: hyper.project || "",
      scenario: hyper.scenario || "",
      algorithm: taskDetail.algorithm_file_id || "", // 算法 file_id
      version: hyper.version || "",
      description: taskDetail.description || "", // 后端如果以后补充 description，就能直接回显
    });

    // 如果有 algorithm_file_id，则根据算法配置回显“数据配置”部分
    if (taskDetail.algorithm_file_id) {
      const algoDetail = await getAlgorithm(taskDetail.algorithm_file_id);
      currentAlgorithmDetail.value = algoDetail || {};

      if (currentAlgorithmDetail.value.dev_env) {
        const devEnv = currentAlgorithmDetail.value.dev_env;

        // 默认优先使用测试环境，没有则使用生产环境
        let apiEnv = null;
        if (devEnv.testing_env) {
          form.value.envSelection = "testing";
          apiEnv = devEnv.testing_env;
        } else if (devEnv.production_env) {
          form.value.envSelection = "production";
          apiEnv = devEnv.production_env;
        }

        if (apiEnv) {
          fillApiConfigFromEnv(apiEnv);
        }
      }
    }
  } catch (error) {
    console.error("获取任务详情失败:", error);
    ElMessage.error("获取任务详情失败");
  }
}

/** 提交按钮 */
async function submitForm() {
  try {
    await proxy.$refs["editForm"].validate();

    // BentoML 接口不支持更新训练任务，这里仅提供查看功能
    ElMessage.warning(
      "BentoML 训练任务创建后不支持修改，该弹窗仅用于查看任务与数据配置详情"
    );
    open.value = false;
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

// 处理下载模型
async function handleDownload(row) {
  try {
    // BentoML 使用 model_tag (即 task_id) 下载模型
    const modelTag = row.task_id || row.model_tag;
    if (!modelTag) {
      ElMessage.error("无法获取模型标签");
      return;
    }

    const response = await downloadTrainingModel(modelTag);

    // 创建下载链接
    const blob = new Blob([response]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `model_${modelTag}.zip`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success("开始下载模型");
  } catch (error) {
    console.error("下载模型失败:", error);
    ElMessage.error("下载模型失败");
  }
}

// 执行训练任务
async function handleExecute(row) {
  try {
    await ElMessageBox.confirm(
      '是否确认执行任务"' + row.task_id + '"?',
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      }
    );

    await executeTrainingTask(row.task_id);
    ElMessage.success("训练任务已开始执行");
    getList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("执行训练任务失败:", error);
      ElMessage.error("执行训练任务失败");
    }
  }
}

// 取消训练任务
async function handleCancel(row) {
  try {
    await ElMessageBox.confirm(
      '是否确认取消任务"' + row.task_id + '"?',
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await cancelTrainingTask(row.task_id);
    ElMessage.success("训练任务已取消");
    getList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("取消训练任务失败:", error);
      ElMessage.error("取消训练任务失败");
    }
  }
}

// 重试训练任务
async function handleRetry(row) {
  try {
    await ElMessageBox.confirm(
      '是否确认重试任务"' + row.task_id + '"?',
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      }
    );

    await retryTrainingTask(row.task_id);
    ElMessage.success("训练任务已重新开始");
    getList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("重试训练任务失败:", error);
      ElMessage.error("重试训练任务失败");
    }
  }
}

// 处理部署模型
function handleDeploy(row) {
  // 跳转到部署页面，传递 task_id (model_tag)
  router.push({
    path: "/model/deployment/create",
    query: { model_tag: row.task_id },
  });
}

// 处理任务ID点击
function handleTaskIdClick(row) {
  router.push(`/model/training/detail/${row.task_id}`);
}

// 初始化
onMounted(() => {
  getStatusOptions();
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.task-id-link {
  font-weight: 500;
  text-decoration: none;
}

.task-id-link:hover {
  text-decoration: underline;
  color: #409eff;
}

.el-button.is-link {
  color: #606266;
}

/* 与 create.vue 保持一致的分块样式 */
.form-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}
</style>
